package com.hkts.beltweigher.opc;

import com.hkts.beltweigher.config.httpclient.HttpAPIService;
import com.hkts.beltweigher.config.httpclient.MsgCache;
import com.hkts.beltweigher.salve.entity.EastBeltscalesInstantaneousdata;
import com.hkts.beltweigher.salve.entity.TemperatureRegulationItem;
import com.hkts.beltweigher.salve.service.IEastBeltscalesInstantaneousdataService;
import com.hkts.beltweigher.salve.service.ITemperatureRegulationItemService;
import com.hkts.beltweigher.utils.SpringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.sdk.client.model.nodes.objects.ServerTypeNode;
import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
import org.eclipse.milo.opcua.stack.core.Identifiers;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @ClassNameHKOneHeadWrite
 * @Description
 * @Author yck
 * @Date16/11/2022 下午4:47
 * @Version V1.0
 **/
@Slf4j
@Service
@Data
public class EastDataAcquisitionClient implements ClientExample {
    private String opcUrl;
    private String tableDescribte;
    private String opcId;
    private HttpAPIService httpAPIService = SpringUtils.getBean("httpAPIService");
    private static ITemperatureRegulationItemService temperatureRegulationItemService = SpringUtils.getBean("temperatureRegulationItemService");
    private static IEastBeltscalesInstantaneousdataService iEastBeltscalesInstantaneousdataService = SpringUtils.getBean("iEastBeltscalesInstantaneousdataService");

    public static void main(String[] args) throws Exception {
        EastDataAcquisitionClient example = new EastDataAcquisitionClient();
        String tEndpointUrl = "opc.tcp://192.168.205.130:4840";
        // String tEndpointUrl = "opc.tcp://192.168.66.2:5000";
        new ClientExampleRunner(example, tEndpointUrl).run();
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {


        // synchronous connect
        CompletableFuture<UaClient> connect = client.connect();
        UaClient uaClient = connect.get();


        // Get a typed reference to the Server object: ServerNode
        ServerTypeNode serverNode = (ServerTypeNode) client.getAddressSpace().getObjectNode(
                Identifiers.Server,
                Identifiers.ServerType
        );

        List<? extends UaNode> uaNodes = client.getAddressSpace().browseNodes(Identifiers.ObjectsFolder);
        boolean bs = true;
        while (bs) {
            StringBuffer buffer = new StringBuffer();
         try {

             List<TemperatureRegulationItem>  items= temperatureRegulationItemService.selectListByOpcId(opcId);
             List<NodeId> list = new ArrayList<>();
             for (int i = 0; i <items.size() ; i++) {
                 NodeId nodeId3 = new NodeId(4,Integer.parseInt(items.get(i).getDataSourceField()) );
                 list.add(nodeId3);
             }
             CompletableFuture<List<DataValue>> listCompletableFuture = client.readValues(0.0, TimestampsToReturn.Neither, list);
             // List<DataValue> dataValues = listCompletableFuture.get();
             List<DataValue> dataValues =new ArrayList<>();
             dataValues.addAll( listCompletableFuture.get());
             for (int i = 0; i <items.size() ; i++) {
                 Object value = dataValues.get(i).getValue().getValue();
                 //本地缓存
                 DataCache.ALLCACHE.put(String.valueOf( items.get(i).getId()),value);
             }
             buffer.append(this.tableDescribte).append("(").append(this.opcUrl).append(")重新链接");
             httpAPIService.sendMessage(MsgCache.OPEN, this.opcUrl, buffer.toString());
         }catch (Exception e){
             log.error("断开链接---------");
             buffer.append(this.tableDescribte).append("(").append(this.opcUrl).append(")断开链接");
             httpAPIService.sendMessage(MsgCache.OFF, this.opcUrl, buffer.toString());
         }
            //dataHandler();
            Thread.sleep(1000);
        }
    }

}
